/**
 * Copyright (C) 2015-2016 Guangzhou Xunhong Network Technology Co., Ltd. All rights reserved.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.jxccp.ui.presenter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.text.TextUtils;

import com.jxccp.im.JXErrorCode;
import com.jxccp.im.callback.JXConnectionListener;
import com.jxccp.im.callback.JXEventListner;
import com.jxccp.im.chat.common.entity.JXCommonQuestion;
import com.jxccp.im.chat.common.entity.JXSatisfication;
import com.jxccp.im.chat.common.message.FileMessage;
import com.jxccp.im.chat.common.message.ImageMessage;
import com.jxccp.im.chat.common.message.JXConversation;
import com.jxccp.im.chat.common.message.JXConversation.SessionStatus;
import com.jxccp.im.chat.common.message.JXMessage;
import com.jxccp.im.chat.common.message.JXMessage.ChatType;
import com.jxccp.im.chat.common.message.JXMessageAttribute;
import com.jxccp.im.chat.common.message.JXMessageUtil;
import com.jxccp.im.chat.common.message.LocationMessage;
import com.jxccp.im.chat.common.message.RichTextMessage;
import com.jxccp.im.chat.common.message.TextMessage;
import com.jxccp.im.chat.common.message.VideoMessage;
import com.jxccp.im.chat.common.message.VoiceMessage;
import com.jxccp.im.chat.manager.JXEventNotifier;
import com.jxccp.im.chat.manager.JXImManager;
import com.jxccp.im.exception.JXException;
import com.jxccp.im.util.log.JXLog;
import com.jxccp.ui.JXUiHelper;
import com.jxccp.ui.R;
import com.jxccp.ui.entities.JXCommodity;
import com.jxccp.ui.entities.JXOrderInfo;
import com.jxccp.ui.entities.ZhuiyiLoanOrderEntity;
import com.jxccp.ui.entities.ZhuiyiProductOrderEntity;
import com.jxccp.ui.listeners.JXDemoMessageListener;
import com.jxccp.ui.model.JXRequestCusServiceTask;
import com.jxccp.ui.model.JXRequestCusServiceTask.RequestCusServiceCallback;
import com.jxccp.ui.service.JXNotifyManager;
import com.jxccp.ui.utils.JXCommonUtils;
import com.jxccp.ui.utils.JXSelectImageUriUtils;
import com.jxccp.ui.view.JXChatView;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class JXChatPresenterImp implements JXChatPresenter, JXDemoMessageListener,
        JXEventListner, JXConnectionListener {

    private JXChatView mChatView;

    private JXConversation mConversation;

    private String subOrgId;

    private ChatType chatType;

    private String skillsId;

    private Handler mainHandler = new Handler(Looper.getMainLooper());

    private AsyncTask<Void, Void, Void> msgFetchTask = null;

    private AsyncTask<Void, Void, Void> getRobotUnsatisfiedReasonsTask = null;

    private AsyncTask<Void, Void, Void> popWindowFetchTask = null;

    private AsyncTask<Void, Void, Void> submitRobotSatisfyTask = null;

    private int errorCode = 0;

    private static final int PAGE_SIZE = 15;

    private int orderStartIndex = 0;

    private int orderRowCount = 10;

    private int zhuiyiProductOrderStartIndex = 0;

    private int zhuiyiProductOrderRowCount = 10;

    private int zhuiyiLoanOrderStartIndex = 0;

    private int zhuiyiLoanOrderRowCount = 10;

    private int commonQuestionPageNo = 1;

    private Context mContext;

    private ExecutorService inputAssociationService = new ThreadPoolExecutor(1, 1,
            0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<Runnable>());

    public JXChatPresenterImp(@NonNull JXChatView chatView, @NonNull String subOrgId,
                              @NonNull ChatType chatType, String skillsId, Context mContext) {
        this.mChatView = chatView;
        this.subOrgId = subOrgId;
        this.chatType = chatType;
        this.skillsId = skillsId;
        this.mContext = mContext;
        mConversation = JXImManager.Conversation.getInstance().getConversation(subOrgId,
                chatType);
        JXImManager.Message.getInstance().registerEventListener(this);
        JXNotifyManager.getInstance().addMessagListener(this);
        JXImManager.Login.getInstance().addConnectionListener(this);
    }

    @Override
    public void sendImageMessage(String filePath) {
        if (!TextUtils.isEmpty(filePath)) {
            ImageMessage imageMessage = null;
            File imageFile = new File(filePath);
            String priviateDir = mContext.getExternalFilesDir("").getAbsolutePath();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && !Environment.isExternalStorageLegacy() && !filePath.startsWith(priviateDir)) {
                //android 10 且是 分区存储模式 且不是私有目录 特殊处理
                String uri = JXSelectImageUriUtils.getImageUriFromPath(mContext,filePath);
                imageMessage = JXMessageUtil.createSendImageMessageForUri(chatType, subOrgId,
                        imageFile,uri);
            } else {
                imageMessage = JXMessageUtil.createSendImageMessage(chatType, subOrgId,
                        imageFile, JXMessage.NO_BURN_AFTER_READ);
            }
            JXImManager.Message.getInstance().sendMessage(imageMessage);
            mChatView.refreshChatView(true, JXChatView.INVAILD_SELECTION);
        } else {
            JXLog.d("[JXChatPresenterImp.sendImageMessage] file path is null or empty");
        }
    }

    @Override
    public void onDestroy() {
        if (cusServiceTask != null) {
            cusServiceTask.clearCallback();
            cusServiceTask.cancel(true);
        }
        if (inputAssociationService != null) {
            inputAssociationService.shutdownNow();
        }
        cancelFetchMsg();
        cancelFetchRobotUnsatisfiedReasons();
        cancelPopWindowFetchTask();
        JXImManager.Message.getInstance().removeEventListener(this);
        JXNotifyManager.getInstance().removeMessageListener(this);
        JXImManager.Login.getInstance().removeConnectionListener(this);
    }

    private boolean moreData = true;

    private boolean loading = false;

    @Override
    public void loadMoreMessages(@Nullable String lastMesageId) {
        if (mChatView != null) {
            if (!loading && moreData) {
                int count;
                if (TextUtils.isEmpty(lastMesageId)) {
                    count = mConversation.loadMoreMessage(null, JXChatView.DEFAULT_PAGE).size();
                } else {
                    count = mConversation.loadMoreMessage(lastMesageId, JXChatView.DEFAULT_PAGE)
                            .size();
                }
                if (count > 0) {
                    mChatView.refreshChatView(false, 19);
                    loading = false;
                } else {
                    moreData = false;
                }
            }
            mChatView.interruptRefresh();
        }
    }

    @Override
    public void onEvent(JXEventNotifier eventNotifier) {
        if (mChatView != null) {
            if (eventNotifier.getEvent() == JXEventNotifier.Event.MESSAGE_PUSH) {
                mChatView.onMessageBoxUpdate();
            } else {
                if (eventNotifier.getData() != null) {
                    final JXMessage message = (JXMessage) eventNotifier.getData();
                    if (!TextUtils.isEmpty(message.getSuborgId()) && !JXUiHelper.getInstance()
                            .getSuborgId().equals(message.getSuborgId())) {
                        return;
                    }
                    if (message.getType() == JXMessage.Type.EVALUATION) {
                        mainHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                fetchEvaluateInfo(message, false);
                            }
                        }, 800);
                    }
                    String extType = message.getStringAttribute(JXMessageAttribute.TYPE.value(),
                            null);
                    String jxuid = message.getStringAttribute(JXMessageAttribute.JXUID.value(),
                            null);
                    String jxaid = message.getStringAttribute(JXMessageAttribute.JXAID.value(),
                            null);
                    //直接转人工
                    if (JXMessageAttribute.TYPE_VALUE_ROBOT_TRANSFER.equals(extType)) {
                        mChatView.autoTransferCustomerService();
                    }
                    //提示机器回答反馈
                    if (!TextUtils.isEmpty(jxuid) && !TextUtils.isEmpty(jxaid)) {
                        JXUiHelper.getInstance().addEnableRobotFeedBackMsgSet(message
                                .getMessageId());
                    }
                    //转人工提示
                    if (JXMessageAttribute.TYPE_VALUE_ROBOT_TRANSFER_TIPS.equals(extType)) {
                        JXUiHelper.getInstance().addTransferTipsMsgSet(message.getMessageId());
                    }
                    //机器人自动结束处理
                    if (JXMessageAttribute.TYPE_VALUE_AUTO_CLOSE_FOR_VISITOR.equals(extType)) {
                        mChatView.autoCloseWithRobot();
                    }
                    if (JXMessageAttribute.TYPE_VALUE_ROBOT_YIBOT_TASK.equals(extType)) {
                        String jxQuestion = message.getStringAttribute(JXMessageAttribute
                                .JXQUESTION.value(), "");
                        boolean productOrderEnable = true;
                        boolean loanOrderEnable = true;
                        if ("取现状态查询".equals(jxQuestion)) {
                            productOrderEnable = false;
                        }
                        if ("咨询发货问题".equals(jxQuestion)) {
                            loanOrderEnable = false;
                        }
                        mChatView.showZhuiyiOrderList(jxQuestion, productOrderEnable,
                                loanOrderEnable);
                    }
                }
                mChatView.refreshChatView(false, JXChatView.INVAILD_SELECTION);
            }
        }
    }

    @Override
    public void onSuccess(JXMessage message) {
        if (mChatView != null) {
            mChatView.refreshChatView(false, JXChatView.INVAILD_SELECTION);
        }
    }

    @SuppressLint("NewApi")
    @Override
    public void onError(final JXMessage message, final int code, String reason) {
        if (mChatView != null) {
            mChatView.refreshChatView(false, JXChatView.INVAILD_SELECTION);
            Context context = null;
            if (mChatView instanceof Activity) {
                context = (Activity) mChatView;
            } else if (mChatView instanceof Fragment) {
                context = ((Fragment) mChatView).getActivity();
            } else if (mChatView instanceof android.app.Fragment) {
                context = ((android.app.Fragment) mChatView).getActivity();
            }
            if (JXErrorCode.Message.FILE_SIZE_EXCEEDED == code
                    || JXErrorCode.Message.FILE_TYPE_MISMATCH == code) {
                if (message instanceof FileMessage) {
                    if (context != null) {
                        @SuppressLint("StringFormatMatches") String tips = JXErrorCode.Message
                                .FILE_TYPE_MISMATCH == code ? context.getString(R.string
                                .jx_file_format_no_match)
                                : String.format(context.getString(R.string.jx_file_over_size),
                                (JXImManager.Config.getInstance().getFileMsgMaxSize(message
                                        .getType()) / 1024));
                        mChatView.showErrorTips(code, tips);
                    }
                }
            } else if (JXErrorCode.Message.SENSITIVE_WORD == code) {
                JXLog.d("[JXChatPresenterImp.messagelistener.onerror] msg contain sensitive word " +
                        ", word = " + reason);
                //您有1 处词语过于敏感，敏感词为： mingan , 系统目前不允许发送，请修改后发送。
                if (context != null) {
                    String[] swords = reason.split(";");
                    String tips = context.getString(R.string.jx_sensitive_word_tips);
                    tips = tips.replace("$1", String.valueOf(swords.length));
                    tips = tips.replace("$2", reason);
                    mChatView.showErrorWindow(code, tips);
                }
            } else {
                JXLog.e("[JXChatPresenterImp.messagelistener.onerror] message send fail code = "
                        + code + " , reason = " + reason);
            }
        }
    }

    @Override
    public void onTransfered(JXMessage message, long totalSize, long currentSize) {
        if (mChatView != null) {
            mChatView.refreshChatView(false, JXChatView.INVAILD_SELECTION);
        }
    }

    @Override
    public void sendTextMessage(String text) {
        if (mChatView != null) {
            TextMessage msg = JXMessageUtil.createSendTextMessage(chatType, subOrgId,
                    text, JXMessage.NO_BURN_AFTER_READ);
            JXImManager.Message.getInstance().sendMessage(msg);
            mChatView.refreshChatView(true, JXChatView.INVAILD_SELECTION);
        }
    }

    @Override
    public void resendMessage(JXMessage jxMessage) {
        if (mChatView != null) {
            JXImManager.Message.getInstance().resendMessage(jxMessage);
            mChatView.refreshChatView(true, JXChatView.INVAILD_SELECTION);
        }
    }

    /*@Override
    public void onRequestCallback(int code, int tag, boolean isNeedFinishAty) {
        if(mChatView != null){
            if(code == 0){
                if(tag != JXRequestCusServiceTask.TAG_NOT_TRANSFER){
                    mChatView.hideProgress();
                }
            }else{
                mChatView.hideProgress();
            }
        }
    }*/

    private JXRequestCusServiceTask cusServiceTask;

    @Override
    public void requestCustomer(String skillsId, String extendData, int Tag, JXMessage
            triggerMsg, RequestCusServiceCallback callback) {
        if (mChatView != null) {
            mChatView.showProgress(Tag);
            cusServiceTask = new JXRequestCusServiceTask(subOrgId, skillsId, extendData, callback,
                    triggerMsg);
            if (Tag != JXUiHelper.TAG_CANCEL_WAIT) {
                cusServiceTask.setTransferTag(Tag, true);
            } else {
                cusServiceTask.setTransferTag(Tag, false);
            }
            cusServiceTask.execute();
        }
    }

    @Override
    public void fetchMessages(final boolean pullToRefresh, final JXMessage jxMessage, final
    ChatType chatType) {
        cancelFetchMsg();
        msgFetchTask = new FetchMessageTake(mChatView, pullToRefresh, chatType, subOrgId,
                skillsId, jxMessage).execute();
    }

    @Override
    public void sendRobotFeedBack(JXMessage message, final Boolean isSatisfy, final String
            unSatisfiedReason) {
        JXUiHelper.getInstance().getEnableRobotFeedBackMsgSet().remove(message.getMessageId());
        JXUiHelper.getInstance().addRobotFeedBackedMsgSet(message.getMessageId());
        mChatView.refreshChatView(false, JXChatView.INVAILD_SELECTION);
        final String uid = (String) message.getAttributes().get(JXMessageAttribute.JXUID.value());
        final String aid = (String) message.getAttributes().get(JXMessageAttribute.JXAID.value());
        final String question = (String) message.getAttributes().get(JXMessageAttribute
                .JXQUESTION.value());
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String result = JXImManager.McsUser.getInstance().sendRobotFeedBack(uid, aid,
                            isSatisfy, question, unSatisfiedReason);
                    JXUiHelper.getInstance().setRobotFeedBackThanksMsg(result);
                    mChatView.refreshChatView(false, JXChatView.INVAILD_SELECTION);
                } catch (JXException e) {
                    JXLog.e("[JXChatPresenterImp.sendRobotFeedBack] send robot feedback exception" +
                            " ", e);
                }
            }
        }).start();
    }

    @Override
    public void getInputAssociationList(final String associationText) {
        if (inputAssociationService != null && !inputAssociationService.isShutdown()) {
            inputAssociationService.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        List<String> inputAssociationList = JXImManager.McsUser.getInstance()
                                .getRobotSmartBox(associationText);
                        if (inputAssociationList != null && inputAssociationList.size() > 0) {
                            mChatView.refreshInputAssociationList(inputAssociationList);
                        }
                    } catch (JXException e) {
                        JXLog.e("[JXChatPresenterImp.getInputAssociationList] exception ", e);
                    }
                }
            });
        }
    }

    @Override
    public void sendChatStateMessage(String state, String stateContent) {
        if (JXImManager.McsUser.getInstance().isPrepareMsgFlagOpen()) {
            JXImManager.McsUser.getInstance().sendChatStateMessage(JXUiHelper.getInstance()
                    .getSuborgId(), state, stateContent);
            mChatView.removeComposingStateMsg();
        }
    }

    @Override
    public void getRobotUnSatisfiedReason(final JXMessage jxMessage) {
        cancelFetchRobotUnsatisfiedReasons();
        getRobotUnsatisfiedReasonsTask = new AsyncTask<Void, Void, Void>() {
            String[] reasonOptionStr = null;

            @Override
            protected Void doInBackground(Void... arg0) {
                List<String> robotUnSatisfiedReason = JXImManager.McsUser.getInstance()
                        .getRobotUnSatisfiedReasons(JXUiHelper.getInstance().getSuborgId());
                if (robotUnSatisfiedReason != null && robotUnSatisfiedReason.size() > 0) {
                    reasonOptionStr = new String[robotUnSatisfiedReason.size()];
                    reasonOptionStr = robotUnSatisfiedReason.toArray(reasonOptionStr);
                }
                return null;
            }

            protected void onPostExecute(Void result) {
                if (mChatView != null) {
                    mChatView.showRobotunsatisfiedDialog(jxMessage, reasonOptionStr);
                }
            }

            ;
        }.execute();
    }

    @Override
    public void fetchEvaluateInfo(final JXMessage evaluateMessage, final boolean isCloseSession) {
        cancelPopWindowFetchTask();
        popWindowFetchTask = new AsyncTask<Void, Void, Void>() {

            JXSatisfication satisfication;

            protected void onPreExecute() {
                mChatView.showProgress(JXUiHelper.TAG_EVALUTE);
            }

            ;

            @Override
            protected Void doInBackground(Void... arg0) {
                satisfication = mConversation.getSatisfication();
                return null;
            }

            protected void onPostExecute(Void result) {
                mChatView.hideProgress();
                mChatView.showEvaluateWindow(satisfication, evaluateMessage, isCloseSession);
            }

            ;
        }.execute();
    }

    @Override
    public void fetchQuickQuestion() {
        cancelPopWindowFetchTask();
        popWindowFetchTask = new AsyncTask<Void, Void, Void>() {

            List<String> questionList = new ArrayList<String>();

            protected void onPreExecute() {
                mChatView.showProgress(JXUiHelper.TAG_QUICK_QUESTION);
            }

            ;

            @Override
            protected Void doInBackground(Void... params) {
                questionList = JXImManager.McsUser.getInstance().getQuickQuestions(JXUiHelper
                        .getInstance().getSuborgId());
                JXLog.d("[JXChatPresenterImp.fetchQuickQuestion] question list = " + questionList);
                return null;
            }

            @SuppressLint("InflateParams")
            @Override
            protected void onPostExecute(Void result) {
                mChatView.hideProgress();
                mChatView.showQuickQuestionWindows(questionList);
            }
        }.execute();
    }

    @Override
    public void fetchOrderList(final boolean refresh) {
        cancelPopWindowFetchTask();
        popWindowFetchTask = new AsyncTask<Void, Void, Void>() {

            List<JXOrderInfo> orderInfoList = new ArrayList<JXOrderInfo>();

            @Override
            protected Void doInBackground(Void... params) {
                try {
                    if (refresh) {
                        orderStartIndex = 0;
                        orderRowCount = JXUiHelper.getInstance()
                                .getThirdPartyOrderDefaultPageSize();
                    }
                    orderInfoList = JXUiHelper.getInstance().fetchThirdPartyOrderList
                            (orderStartIndex, JXUiHelper.getInstance()
                                    .getThirdPartyOrderDefaultPageSize());
                } catch (Exception e) {
                    JXLog.e("[JXChatPresenterImp.fetchOrderList] fetch order exception ", e);
                }
                JXLog.d("[JXChatPresenterImp.fetchOrderList] order list = " + orderInfoList);
                return null;
            }

            @SuppressLint("InflateParams")
            @Override
            protected void onPostExecute(Void result) {
                boolean hasMore = false;
                if (orderInfoList != null && orderInfoList.size() == PAGE_SIZE) {
                    hasMore = true;
                    orderStartIndex = orderRowCount;
                    orderRowCount = orderRowCount + orderInfoList.size();
                }
                mChatView.refreshOrderList(orderInfoList, hasMore, refresh);
            }
        }.execute();
    }

    @Override
    public void fetchcommonQuestionList(final boolean refresh) {
        cancelPopWindowFetchTask();
        popWindowFetchTask = new AsyncTask<Void, Void, Void>() {

            List<JXCommonQuestion> commonQuestionList = new ArrayList<JXCommonQuestion>();

            @Override
            protected Void doInBackground(Void... params) {
                try {
                    if (refresh) {
                        commonQuestionPageNo = 1;
                    }
                    commonQuestionList = JXImManager.McsUser.getInstance().getCommonQuestion
                            (commonQuestionPageNo, PAGE_SIZE);
                } catch (Exception e) {
                    JXLog.e("[JXChatPresenterImp.fetchcommonQuestionList] fetch commonQuestion " +
                            "exception ", e);
                }
                JXLog.d("[JXChatPresenterImp.fetchcommonQuestionList] commonQuestion list = " +
                        commonQuestionList);
                return null;
            }

            @SuppressLint("InflateParams")
            @Override
            protected void onPostExecute(Void result) {
                boolean hasMore = false;
                if (commonQuestionList != null && commonQuestionList.size() == PAGE_SIZE) {
                    hasMore = true;
                    commonQuestionPageNo++;
                }
                mChatView.refreshCommonQuestionList(commonQuestionList, hasMore, refresh);
            }
        }.execute();
    }

    @Override
    public void fetchZhuiyiProductList(final boolean refresh) {
        cancelPopWindowFetchTask();
        popWindowFetchTask = new AsyncTask<Void, Void, Void>() {

            List<ZhuiyiProductOrderEntity> zhuiyiProductOrderInfoList = new
                    ArrayList<ZhuiyiProductOrderEntity>();

            @Override
            protected Void doInBackground(Void... params) {
                try {
                    if (refresh) {
                        zhuiyiProductOrderStartIndex = 0;
                        zhuiyiProductOrderRowCount = JXUiHelper.getInstance()
                                .getThirdPartyOrderDefaultPageSize();
                    }
                    zhuiyiProductOrderInfoList = JXUiHelper.getInstance()
                            .fetchZhuiyiProductOrderList
                                    (zhuiyiProductOrderStartIndex, JXUiHelper.getInstance()
                                            .getThirdPartyOrderDefaultPageSize());
                } catch (Exception e) {
                    JXLog.e("[JXChatPresenterImp.fetchOrderList] fetch order exception ", e);
                }
                JXLog.d("[JXChatPresenterImp.fetchOrderList] order list = " +
                        zhuiyiProductOrderInfoList);
                return null;
            }

            @SuppressLint("InflateParams")
            @Override
            protected void onPostExecute(Void result) {
                boolean hasMore = false;
                if (zhuiyiProductOrderInfoList != null && zhuiyiProductOrderInfoList.size() ==
                        PAGE_SIZE) {
                    hasMore = true;
                    zhuiyiProductOrderStartIndex = zhuiyiProductOrderRowCount;
                    zhuiyiProductOrderRowCount = zhuiyiProductOrderRowCount +
                            zhuiyiProductOrderInfoList.size();
                }
                mChatView.refreshZhuiyiProductOrderList(zhuiyiProductOrderInfoList, hasMore,
                        refresh);
            }
        }.execute();
    }

    @Override
    public void fetchZhuiyiLoanList(final boolean refresh) {
        cancelPopWindowFetchTask();
        popWindowFetchTask = new AsyncTask<Void, Void, Void>() {

            List<ZhuiyiLoanOrderEntity> zhuiyLoanOrderInfoList = new
                    ArrayList<ZhuiyiLoanOrderEntity>();

            @Override
            protected Void doInBackground(Void... params) {
                try {
                    if (refresh) {
                        zhuiyiLoanOrderStartIndex = 0;
                        zhuiyiLoanOrderRowCount = JXUiHelper.getInstance()
                                .getThirdPartyOrderDefaultPageSize();
                    }
                    zhuiyLoanOrderInfoList = JXUiHelper.getInstance().fetchZhuiyiLoanOrderList
                            (zhuiyiLoanOrderStartIndex, JXUiHelper.getInstance()
                                    .getThirdPartyOrderDefaultPageSize());
                } catch (Exception e) {
                    JXLog.e("[JXChatPresenterImp.fetchOrderList] fetch order exception ", e);
                }
                JXLog.d("[JXChatPresenterImp.fetchOrderList] order list = " +
                        zhuiyLoanOrderInfoList);
                return null;
            }

            @SuppressLint("InflateParams")
            @Override
            protected void onPostExecute(Void result) {
                boolean hasMore = false;
                if (zhuiyLoanOrderInfoList != null && zhuiyLoanOrderInfoList.size() == PAGE_SIZE) {
                    hasMore = true;
                    zhuiyiLoanOrderStartIndex = zhuiyiLoanOrderRowCount;
                    zhuiyiLoanOrderRowCount = zhuiyiLoanOrderRowCount + zhuiyLoanOrderInfoList
                            .size();
                }
                mChatView.refreshZhuiyiLoanOrderList(zhuiyLoanOrderInfoList, hasMore, refresh);
            }
        }.execute();
    }

    @Override
    public void sendZhuiyiProductOrderMessage(ZhuiyiProductOrderEntity zhuiyiProductOrderEntity,
                                              String jxQuestion) {
        JXLog.d("[JXChatPresenterImp.sendZhuiyiProductOrderMessage] zhuiyi product order = " +
                zhuiyiProductOrderEntity);
        if (zhuiyiProductOrderEntity != null) {
            try {
                RichTextMessage orderMessage = JXMessageUtil.createSendRichMessage(ChatType
                                .CUSTOMER_SERVICE, subOrgId,
                        zhuiyiProductOrderEntity.getProductList().get(0).getProductName(),
                        zhuiyiProductOrderEntity.getProductList().get(0)
                                .getProductdescription(), null,
                        zhuiyiProductOrderEntity.getProductList().get(0).getProductImgUrl());
                orderMessage.setAttributes(JXMessageAttribute.JXQUESTION.value(), jxQuestion);
                orderMessage.setAttributes(JXMessageAttribute.ORDER_MESSAGE_TIME.value(),
                        zhuiyiProductOrderEntity.getOrderTime());
                orderMessage.setAttributes(JXMessageAttribute.ORDER_MESSAGE_STATUS.value(),
                        zhuiyiProductOrderEntity.getOrderStatus());
                orderMessage.setAttributes(JXMessageAttribute.ORDER_MESSAGE_AMOUNT.value(),
                        zhuiyiProductOrderEntity.getProductList().get(0).getProductPrice());
                orderMessage.setAttributes(JXMessageAttribute.ORDER_MESSAGE_ID.value(),
                        zhuiyiProductOrderEntity.getOrderId());
                orderMessage.setAttributes(JXMessageAttribute.ORDER_MESSAGE_PAYNUM.value(),
                        zhuiyiProductOrderEntity.getProductTotalNum());
                orderMessage.setAttributes(JXMessageAttribute.ORDER_MESSAGE_PAYMENT.value(),
                        zhuiyiProductOrderEntity.getOrderTotalPay());
                orderMessage.setAttributes(JXMessageAttribute.ORDER_MESSAGE_PAYTIME.value(),
                        zhuiyiProductOrderEntity.getOrderPayTime());
                orderMessage.setAttributes(JXMessageAttribute.ORDER_MESSAGE_CATEGROY.value(),
                        String.valueOf(zhuiyiProductOrderEntity.getOrderTradeType()));
                orderMessage.setAttributes(JXMessageAttribute.ORDER_MESSAGE_SIGNTIME.value(),
                        zhuiyiProductOrderEntity.getOrderSignTime());
                JXImManager.Message.getInstance().sendMessage(orderMessage);
                mChatView.refreshChatView(true, JXChatView.INVAILD_SELECTION);
            } catch (Exception e) {
                JXLog.e("[JXChatPresenterImp.sendZhuiyiProductOrderMessage] send zhuiyi product " +
                        "order exceptiong , order= " + zhuiyiProductOrderEntity, e);
            }
        }
    }

    @Override
    public void sendZhuiyiLoantOrderMessage(ZhuiyiLoanOrderEntity zhuiyiLoanOrderEntity, String
            jxQuestion) {
        JXLog.d("[JXChatPresenterImp.sendZhuiyiLoantOrderMessage] zhuiyi loan order = " +
                zhuiyiLoanOrderEntity);
        if (zhuiyiLoanOrderEntity != null) {
            try {
                RichTextMessage orderMessage = JXMessageUtil.createSendRichMessage(ChatType
                                .CUSTOMER_SERVICE, subOrgId,
                        zhuiyiLoanOrderEntity.getLoanReason(), zhuiyiLoanOrderEntity
                                .getLoanReason(), null,
                        "");
                orderMessage.setAttributes(JXMessageAttribute.ORDER_MESSAGE_TIME.value(),
                        zhuiyiLoanOrderEntity.getOrderTime());
                orderMessage.setAttributes(JXMessageAttribute.ORDER_MESSAGE_STATUS.value(),
                        String.valueOf(zhuiyiLoanOrderEntity.getOrderStatus()));
                orderMessage.setAttributes(JXMessageAttribute.ORDER_MESSAGE_AMOUNT.value(),
                        zhuiyiLoanOrderEntity.getLoanAmt());
                orderMessage.setAttributes(JXMessageAttribute.ORDER_MESSAGE_ID.value(),
                        zhuiyiLoanOrderEntity.getOrderId());
                orderMessage.setAttributes(JXMessageAttribute.ORDER_MESSAGE_TYPE.value(), String
                        .valueOf(zhuiyiLoanOrderEntity.getLoanType()));
                orderMessage.setAttributes(JXMessageAttribute.JXQUESTION.value(), jxQuestion);
                JXImManager.Message.getInstance().sendMessage(orderMessage);
                mChatView.refreshChatView(true, JXChatView.INVAILD_SELECTION);
            } catch (Exception e) {
                JXLog.e("[JXChatPresenterImp.sendZhuiyiLoantOrderMessage] send zhuiyi loan order " +
                        "exceptiong , order= " + zhuiyiLoanOrderEntity, e);
            }
        }
    }

    @Override
    public void saveEvaluateFeedbackMessage(String msg) {
        JXImManager.McsUser.getInstance().saveEvaluateFeedbackMessage(JXUiHelper.getInstance()
                        .getSuborgId(), "",msg);
        mChatView.refreshChatView(false, JXChatView.INVAILD_SELECTION);
    }

    @Override
    public void submitRobotSatisfy() {
        if (submitRobotSatisfyTask != null) {
            submitRobotSatisfyTask.cancel(true);
            submitRobotSatisfyTask = null;
        }
        submitRobotSatisfyTask = new AsyncTask<Void, Void, Void>() {

            @Override
            protected Void doInBackground(Void... arg0) {
                JXImManager.McsUser.getInstance()
                        .submitRobotSatisfy(JXUiHelper.getInstance().getSuborgId());
                return null;
            }

        }.execute();
    }

    @Override
    public void sendLocationMsg(String label, String lat, String lot, String baseImg) {
        LocationMessage locationMessage = JXMessageUtil.createSendLocationMessage(chatType, subOrgId,
                label, Double.parseDouble(lat), Double.parseDouble(lot),baseImg);
        JXImManager.Message.getInstance().sendMessage(locationMessage);
        mChatView.refreshChatView(true, JXChatView.INVAILD_SELECTION);
    }

    @SuppressLint("NewApi")
    @Override
    public void copyTextMessage(String message) {
        Context context = null;
        if (mChatView instanceof Activity) {
            context = (Activity) mChatView;
        } else if (mChatView instanceof Fragment) {
            context = ((Fragment) mChatView).getActivity();
        } else if (mChatView instanceof android.app.Fragment) {
            context = ((android.app.Fragment) mChatView).getActivity();
        }
        if (context != null) {
            // 获取剪贴板管理服务
            ClipboardManager cm = (ClipboardManager) context.getSystemService(
                    Context.CLIPBOARD_SERVICE);
            // 将文本数据复制到剪贴板
            ClipData clip = ClipData.newPlainText("simple text",
                    message);
            cm.setPrimaryClip(clip);
        }
    }

    @Override
    public void deleteMessage(JXMessage jxMessage) {
        if (mChatView != null && mConversation != null) {
            mConversation.removeMessage(jxMessage.getMessageId());
            mChatView.refreshChatView(false, JXChatView.INVAILD_SELECTION);
        }
    }

    @Override
    public void sendVoiceMessage(String filePath, int voiceDur) {
        if (!TextUtils.isEmpty(filePath)) {
            File voiceFile = new File(filePath);
            VoiceMessage voiceMessage = JXMessageUtil.createSendVoiceMessage(chatType, subOrgId,
                    voiceFile, voiceDur, JXMessage.NO_BURN_AFTER_READ);
            JXImManager.Message.getInstance().sendMessage(voiceMessage);
            mChatView.refreshChatView(true, JXChatView.INVAILD_SELECTION);
        } else {
        }
    }

    @Override
    public void onConnected() {
        // TODO Auto-generated method stub

    }

    @Override
    public void onDisconnectioned(int errorCode) {
        if (mConversation.getSessionStatus() == SessionStatus.Waiting) {
            mChatView.closeOnDisconnect();
        }
    }

    @Override
    public void onReconnecting() {
        // TODO Auto-generated method stub

    }

    @Override
    public void sendVideoMessage(String filePath) {
        if (!TextUtils.isEmpty(filePath)) {
            String priviateDir = mContext.getExternalFilesDir("").getAbsolutePath();
            int duration = 1000;
            VideoMessage videoMessage = null;
            File videoFile = new File(filePath);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && !Environment.isExternalStorageLegacy() && !filePath.startsWith(priviateDir)) {
                //android 10 且是 分区存储模式 且不是私有目录 特殊处理
                String uri = JXSelectImageUriUtils.getVideoUriFromPath(mContext, filePath);
                Uri videoUri = Uri.parse(uri);
                duration = JXCommonUtils.getVideoDuration(mContext, videoUri);
                videoMessage = JXMessageUtil.createSendVideoMessage(chatType, subOrgId,
                        videoFile, duration, JXMessage.NO_BURN_AFTER_READ);
                videoMessage.setUri(uri);
            } else {
                duration = JXCommonUtils.getVideoDuration(new File(filePath));
                videoMessage = JXMessageUtil.createSendVideoMessage(chatType, subOrgId,
                        videoFile, duration, JXMessage.NO_BURN_AFTER_READ);
            }
            JXImManager.Message.getInstance().sendMessage(videoMessage);
            mChatView.refreshChatView(true, JXChatView.INVAILD_SELECTION);
        } else {
        }
    }

    @Override
    public void sendCommodityMessage(JXCommodity commodity) {
        if (commodity != null) {
            try {
                RichTextMessage message = JXMessageUtil.createSendRichMessage(ChatType
                                .CUSTOMER_SERVICE, subOrgId,
                        commodity.title, commodity.content, commodity.url, commodity.imgUrl);
                JXImManager.Message.getInstance().sendMessage(message);
                mChatView.refreshChatView(true, JXChatView.INVAILD_SELECTION);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void sendOrderMessage(JXOrderInfo orderInfo) {
        if (orderInfo != null) {
            RichTextMessage orderMessage = JXMessageUtil.createSendRichMessage(ChatType
                            .CUSTOMER_SERVICE, subOrgId,
                    orderInfo.getOrderId(), orderInfo.getStoreName(), orderInfo.getProdUrl(),
                    orderInfo.getStoreLogoUrl());
//            orderMessage.setAttributes(JXMessageAttribute.TYPE_VALUE_ORDER_MESSAGE, true);
            orderMessage.setAttributes(JXMessageAttribute.ORDER_MESSAGE_TIME.value(), orderInfo
                    .getOrderCreatTime());
            JXImManager.Message.getInstance().sendMessage(orderMessage);
            mChatView.refreshChatView(true, JXChatView.INVAILD_SELECTION);
        }
    }

    private void cancelFetchMsg() {
        if (msgFetchTask != null) {
            msgFetchTask.cancel(true);
            msgFetchTask = null;
        }
    }

    private void cancelFetchRobotUnsatisfiedReasons() {
        if (getRobotUnsatisfiedReasonsTask != null) {
            getRobotUnsatisfiedReasonsTask.cancel(true);
            getRobotUnsatisfiedReasonsTask = null;
        }
    }

    private void cancelPopWindowFetchTask() {
        if (popWindowFetchTask != null) {
            popWindowFetchTask.cancel(true);
            popWindowFetchTask = null;
        }
    }

    private static class FetchMessageTake extends AsyncTask<Void, Void, Void> {

        private WeakReference<JXChatView> mJXChatView;

        private boolean pullToRefresh = false;

        private ChatType chatType;

        private String subOrgId;

        private String skillsId;

        private JXMessage jxMessage;

        private int errorCode;

        public FetchMessageTake(JXChatView jxChatView, boolean pullToRefresh, ChatType chatType,
                                String subOrgId, String skillsId, JXMessage jxMessage) {
            mJXChatView = new WeakReference<>(jxChatView);
            this.pullToRefresh = pullToRefresh;
            this.chatType = chatType;
            this.subOrgId = subOrgId;
            this.skillsId = skillsId;
            this.jxMessage = jxMessage;
        }

        List<JXMessage> jxMessages = null;

        @Override
        protected Void doInBackground(Void... arg0) {
            if (chatType == ChatType.CUSTOMER_SERVICE || chatType == null) {
                try {
                    jxMessages = JXImManager.McsUser.getInstance().getMessageHistory
                            (subOrgId, skillsId,
                                    jxMessage == null ? null : jxMessage.getMessageId(),
                                    PAGE_SIZE);
                } catch (JXException e) {
                    errorCode = e.getErrorCode();
                    JXLog.e("[JXChatPresenterImp.fetchMessages]occur jx exception when fetch " +
                            "message =", e);
                } catch (Exception e) {
                    errorCode = JXErrorCode.OTHER;
                    JXLog.e("[JXChatPresenterImp.fetchMessages]occur other exception when " +
                            "fetch message =", e);
                }
            }
            return null;
        }

        protected void onPostExecute(Void result) {
            JXChatView jxChatView = mJXChatView.get();
            if (jxChatView != null && errorCode == 0 && !isCancelled()) {
                JXLog.d("[JXChatPresenterImp.fetchMessages]refresh view");
                if (pullToRefresh) {
                    int position = jxMessages.size() - 1;
                    jxChatView.refreshChatView(false, position);
                    jxChatView.interruptRefresh();
                } else {
                    jxChatView.refreshChatView(true, JXChatView.INVAILD_SELECTION);
                }
            }
        }
    }
}
